//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System.Text.RegularExpressions;
using System.Xml;
using CommunityServer.Components;

namespace CommunityServer.Blogs.Components
{
	/// <summary>
	/// Summary description for CollapseModule.
	/// </summary>
	public class ImageAttachmentModule : ICSModule
	{
		public ImageAttachmentModule() { }

		public void Init(CSApplication csa, XmlNode node)
		{
			csa.PreRenderPost += new CSPostEventHandler(csa_PreRenderPost);
		}

		private void csa_PreRenderPost(IContent content, CSPostEventArgs e)
		{
			if(e.ApplicationType == ApplicationType.Weblog)
			{
				WeblogPost post = content as WeblogPost;
				if(post != null)
				{
					// Make sure it has an [ImageAttachment] in the body
					if(post.FormattedBody.ToLower().IndexOf("[imageattachment") == -1)
						return;

					// Make sure the post has an attachment
					if(!post.HasAttachment)
						return;

					// Make sure the posts's attachment type starts with "image"
					if(!post.Attachment.ContentType.StartsWith("image"))
						return;

					// Format the image tag and place it in the body.
					string imageUrl = string.Format("<img src=\"{0}\" alt=\"Attachment: {1} ({2} bytes)\" border=\"0\" />", BlogUrls.Instance().AttachmentUrl(post.Weblog, post.Attachment), post.AttachmentFilename, post.Attachment.Length);
					RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled;
					post.FormattedBody = Regex.Replace(post.FormattedBody, "\\[imageattachment(\\s*)\\]", imageUrl, options);
				}
			}
		}

	}
}
